package com.practice.designMode.responsibilityChain.validation;

import com.practice.designMode.responsibilityChain.annotion.Length;
import com.practice.designMode.responsibilityChain.annotion.Max;
import com.practice.designMode.responsibilityChain.annotion.Min;
import com.practice.designMode.responsibilityChain.exception.ValidatorException;

import java.lang.reflect.Field;

public class Validator {

    public void validate(Object bean){
        Class<?> beanClass = bean.getClass();
        for (Field declaredField : beanClass.getDeclaredFields()) {
            declaredField.setAccessible(true);
            ValidatorChain validatorChain = buildValidatorChain(declaredField);
            try {
                validatorChain.validate(declaredField.get(bean));
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private ValidatorChain buildValidatorChain(Field declaredField) {
        ValidatorChain validatorChain = new ValidatorChain();
        Length length = declaredField.getAnnotation(Length.class);
        if(length!= null){
            validatorChain.addValidatorHandler(new LengthValidatorHandler(length.value()));
        }
        Max max = declaredField.getAnnotation(Max.class);
        if(max!= null){
            validatorChain.addValidatorHandler(new MaxValidatorHandler(max.value()));
        }
        Min min = declaredField.getAnnotation(Min.class);
        if(min!= null){
            validatorChain.addValidatorHandler(new MinValidatorHandler(min.value()));
        }
        return validatorChain;
    }
}
